//
//  MainViewController.swift
//  VVbo
//
//  Created by Mr.Run on 2017/8/21.
//  Copyright © 2017年 Mr.Run. All rights reserved.
//

import UIKit
import SVProgressHUD

class MainViewController: UITabBarController {
    
    fileprivate var timer:Timer?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setChildControllers()
        setupComposeButton()
        setupTimer()
        delegate = self
        setupNewfeatureViews()
        NotificationCenter.default.addObserver(self, selector: #selector(userlogin), name: NSNotification.Name(rawValue: UserShouldLoginNotification), object: nil)
        
    }
    
    deinit {
        timer?.invalidate()
        NotificationCenter.default.removeObserver(self)
    }
    
    func userlogin(n: Notification) {
//        print("用户登录通知\(n)")
        
        var when = DispatchTime.now()
        
        if n.object != nil{
            SVProgressHUD.setDefaultMaskType(SVProgressHUDMaskType.gradient)
            SVProgressHUD.showInfo(withStatus: "用户登录超时, 需要重新登录")
            when = DispatchTime.now() + 2
        }
        
        DispatchQueue.main.asyncAfter(deadline: when) {
            SVProgressHUD.setDefaultMaskType(SVProgressHUDMaskType.clear)
            let nav = UINavigationController(rootViewController: OAuthViewController())
            self.present(nav, animated: true, completion: nil)
        }
    }
    
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return .portrait
    }
    
    @objc fileprivate func composeStatus() {
        print("zhuanxie")
        
        // FIXME: 判断登录
        
        let v = ComposeTypeView.composeTypeView()
        v.show { [weak v] (clsName) in
            guard let clsName = clsName,
                let cls = NSClassFromString(Bundle.main.nameSpace + "." + clsName) as? UIViewController.Type
                else{
                    v?.removeFromSuperview()
                    return
            }
            
            let vc = cls.init()
            let nav = UINavigationController(rootViewController: vc)
            nav.view.layoutIfNeeded()
            self.present(nav, animated: true, completion: {
                v?.removeFromSuperview()
            })
            
        }
    }
    
    fileprivate lazy var composeButton: UIButton = UIButton.cz_imageButton("tabbar_compose_icon_add", backgroundImageName: "tabbar_compose_button")
    
}

extension MainViewController {
    
    fileprivate func setupNewfeatureViews() {
        
        if !NetworkManager.shared().userLogon {
            return
        }
        
        let v = isNewVersion ? NewFeatureView.newFeatureView() : WelcomeView.welcomeView()
//        v.frame = view.bounds
        view.addSubview(v)
    }
    
    private var isNewVersion:Bool {
        
//        print(Bundle.main.infoDictionary ?? [:])
//        CFBundleShortVersionString
        
        let currentVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? ""
        let path:String = ("version" as NSString).cz_appendDocumentDir()
        let sandbosVersion = (try? String(contentsOfFile: path)) ?? ""
        
        try? currentVersion.write(toFile: path, atomically: true, encoding: .utf8)
        
        // FIXME: 更改
        return currentVersion != sandbosVersion
    }
    
}

extension MainViewController: UITabBarControllerDelegate {
    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
//        print("将要切换的控制器\(viewController)")
        
        let idx = childViewControllers.index(of: viewController)
        if selectedIndex == 0 && selectedIndex == idx{
//            print("点击了首页")
        }
        
        let nav = childViewControllers[0] as! UINavigationController
        let vc = nav.childViewControllers[0] as! HomeViewController
        vc.tableView?.setContentOffset(CGPoint(x: 0, y: -64), animated: true)
        
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+1) { 
            vc.loadData()
        }
        
        vc.tabBarItem.badgeValue = nil
        UIApplication.shared.applicationIconBadgeNumber = 0
        return !viewController .isMember(of: UIViewController.self)
    }
}

extension MainViewController{
    
    fileprivate func setupTimer() {
        timer = Timer.scheduledTimer(timeInterval: 6000.0, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true)
    }
    
    @objc fileprivate func updateTimer(){
        
        if !NetworkManager.shared().userLogon {
            return
        }
        
        NetworkManager.shared().unreadCount { (count) in
            self.tabBar.items?.first?.badgeValue = count>0 ? "\(count)" : nil
            UIApplication.shared.applicationIconBadgeNumber = count
        }
    }
    
}

extension MainViewController{
    
    fileprivate func setupComposeButton() {
        tabBar.addSubview(composeButton)
        
        let count = CGFloat(childViewControllers.count)
        let w = tabBar.bounds.width/count
        composeButton.frame = tabBar.bounds.insetBy(dx: 2*w, dy: 0)
        composeButton.addTarget(self, action:#selector(composeStatus), for: .touchUpInside)
    }
    
    fileprivate func setChildControllers() {
        
        let docDir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        let jsonPath = (docDir as NSString).appendingPathComponent("main.json")
        
        var data = NSData(contentsOfFile: jsonPath)
        if data == nil {
            let path = Bundle.main.path(forResource: "main.json", ofType: nil)
            data = NSData(contentsOfFile: path!)
        }
        
        guard let array = try? JSONSerialization.jsonObject(with: data! as Data, options: []) as? [[String : Any]]
            else {
            return
        }
        
//        let array: [[String : Any]] = [
//            ["clsName": "HomeViewController", "title": "首页", "imageName": "home",
//             "visitorInfo": ["imageName": "", "message": "关注一些人, 回这里看看有什么惊喜"]
//            ],
//            
//            ["clsName": "MessageViewController", "title": "消息", "imageName": "message_center",
//             "visitorInfo": ["imageName": "visitordiscover_image_message", "message": "登录后, 别人评论你的微博, 发给你的消息, 都会在这里收到通知"]],
//            
//            ["clsName": "UIViewController"],
//            
//            ["clsName": "DiscoverViewController", "title": "发现", "imageName": "discover",
//             "visitorInfo": ["imageName": "visitordiscover_image_message", "message": "登录后, 别人评论你的微博, 发给你的消息, 不再会与实时潮流擦肩而过"]],
//            
//            ["clsName": "ProfileViewController", "title": "我", "imageName": "profile",
//             "visitorInfo": ["imageName": "visitordiscover_image_profile", "message": "登录后, 你的微博, 相册, 个人资料会显示在这里, 展示给别人看"]]
//            ]
        
        // TODO: ->/Users/lemontree/Desktop/
//        let data = try!JSONSerialization.data(withJSONObject: array, options: [.prettyPrinted])
//        (data as NSData).write(toFile: "/Users/lemontree/Desktop/main.json", atomically: true)
        
        var arrayM = [UIViewController]()
        for dict in array! {
            arrayM.append(controller(dict: dict))
        }
        viewControllers = arrayM
    }
    
    
    
    
    private func controller(dict: [String: Any]) ->UIViewController {
        
        guard let clsName = dict["clsName"] as? String,
            let title = dict["title"] as? String,
            let imageName = dict["imageName"] as? String,
            let cls = NSClassFromString(Bundle.main.nameSpace + "." + clsName) as? BaseController.Type,
            let visitorDict = dict["visitorInfo"] as? [String: String]
        
            else {
            return UIViewController()
        }
        let vc = cls.init()
        vc.title = title
        vc.visitorInfoDic = visitorDict
        vc.tabBarItem.image = UIImage(named: "tabbar_" + imageName)
        vc.tabBarItem.selectedImage = UIImage(named: "tabbar_" + imageName + "_selected")?.withRenderingMode(.alwaysOriginal)
        vc.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.orange], for: .selected)
//        vc.tabBarItem.setTitleTextAttributes([NSFontAttributeName: UIFont.systemFont(ofSize: 12)], for: UIControlState(rawValue:0))
        let nav = MainNavigationController(rootViewController: vc)
        return nav
    }
    
}
